package hrms.service;

import java.sql.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;

import hrms.dao.AdminDao;
import hrms.dao.DeptDao;
import hrms.entity.Admin;
import hrms.entity.Dept;
import hrms.util.PageUtil;
import hrms.util.Result;

@Service("deptService")
public class DeptServiceImpl implements DeptService{
	
	@Resource(name="adminDao")
	private AdminDao adminDao ;
	
	@Resource(name="deptDao")
	private DeptDao dao;

	
	public Result<List<Dept>> findByPage(String pages ,HttpServletResponse res) {
		String message = "Dept";
		Result<List<Dept>> result = new PageUtil<Dept>().findByPage(pages, res, dao, message);
		List<Dept> list = result.getData();
		for(Dept d : list){
			d.setdEmps(dao.findEmps(d.getdeptId()));
			dao.setEmps(d.getdEmps(),d.getdeptId());
		}
		return result;
	}
	
	public Result<Map<String, Integer>> pageTotal(HttpServletRequest req){
		String message = "Dept";
		return PageUtil.pageTotal(req, message);
	}
	
	public Result<Object> deleteDept(String deptId ,HttpServletRequest req) {
		//获取当前登录的用户
		Admin adminUser = (Admin)req.getSession().getAttribute("admin");
		Integer rollUser = adminUser.getRoll();
		//获取将要被删除的部门号
		
		if(rollUser != 0 ){
			Result<Object> result = new Result<Object>();
			result.setStatus(2);
			result.setMsg("权限不够!");
			return result;
		}
		Result<Object> result = new Result<Object>();
		int id = Integer.parseInt(deptId);
		int num = dao.deleteDept(id);
		
		Cookie[] c = req.getCookies();
		String page = "1";
		for(Cookie cc : c){
			if(cc.getName().equals("DeptPage")){
				page = cc.getValue();
			}
		}
		int pageNum = Integer.parseInt(page);
		if(num != 1){
			result.setStatus(1);
			result.setMsg("删除出错");
		} else {
			dao.updateDelete(id);
			dao.updateDefaultDept();
			result.setStatus(0);
			result.setMsg("删除成功");
			result.setData(pageNum);
		}
		return result;
	}

	public Result<Object> addDept(String deptName, String deptTask) {
		Result<Object> result = new Result<Object>();
		List<Dept> list = dao.findAll(1, dao.findRow());
		for(Dept d : list){
			if(d.getdName().equals(deptName)){
				result.setStatus(2);
				return result;
			}
		}
		Dept d = new Dept();
		d.setcreateTime(new Date(System.currentTimeMillis()));
		d.setdEmps(0);
		d.setDescr(deptTask);
		d.setdName(deptName);
		int num = dao.saveDept(d);
		if(num!=1){
			result.setStatus(1);
			result.setMsg("创建出错！");
		} else {
			result.setStatus(0);
			result.setMsg("创建成功！");
		}
		return result;
	}

	public Result<List<Dept>> search(String name) {
		// TODO Auto-generated method stub
		return null;
	}

}
